#include "serverconnector.h"
#include "serverconnection.h"

#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define MAXSLEEP 12

ServerConnector::ServerConnector( int argv , const char **args ) {
	int port = atoi( args[2] ) ;
	memset( &serverAddr , 0 , sizeof(serverAddr) ) ;
	serverAddr.sin_family 		= AF_INET ;
	serverAddr.sin_port   		= htons(port)  ;
	serverAddr.sin_addr.s_addr  = inet_addr( args[1] ) ;
}

ServerConnection ServerConnector::build() {
	int numsec , fd ;
	for ( numsec = 1 ; numsec <= MAXSLEEP ; numsec <<= 1 ) {
		if ( (fd = socket(AF_INET , SOCK_STREAM , 0)) <0 )
			return ServerConnection(-1) ;
		if ( connect(fd , (struct sockaddr*)&serverAddr , sizeof(serverAddr)) == 0 )
			return ServerConnection(fd) ;
		close(fd) ;
		if (numsec <= MAXSLEEP / 2)
			sleep(numsec) ;
	}
	return ServerConnection(-1) ;
}
